﻿using Kz.Telegram.Bot.Console.HandleUpdate;
using Kz.Telegram.Bot.Infrastructure.Extensions;
using Microsoft.Extensions.Logging;
using System.Threading;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Kz.Telegram.Bot.Console
{
    public class Bot(ILogger<Bot> logger)
    {
        const string token = "6718180268:AAFNIzUIr0HxUcegztLlQLpP_u74Fxe1Cfc";

        ILogger<Bot> _logger = logger;

        TelegramBotClient bot = default;

        public async void Run()
        {
            bot = new TelegramBotClient(token);
            bot.Timeout = TimeSpan.FromSeconds(30);
            bot.OnMessage += _OnMessage;
            bot.OnError += _OnError;
            //botClient.OnApiResponseReceived += BotClient_OnApiResponseReceived;
            bot.OnUpdate += _OnUpdate;

            //获取本机器人信息
            using CancellationTokenSource testToken = new();
            try
            {
                await bot.TestApi(testToken.Token);
            }
            catch (Exception ex)
            {
                testToken.Cancel(true);
                System.Console.WriteLine(ex.ToJson());
            }

            //var updates = await botClient.GetUpdates();
            //var receiverOptions = new ReceiverOptions()
            //{
            //    AllowedUpdates = [] // 接收所有更新类型 
            //};

            //botClient.StartReceiving(
            //    updateHandler: HandleUpdateAsync,
            //    errorHandler: HandlePollingErrorAsync,
            //    receiverOptions: receiverOptions
            //);

            #region 设置命令

            //List<BotCommand> cmds = new();
            //cmds.Add(new() { Command = "/start", Description = "打开设置菜单" });
            //cmds.Add(new() { Command = "/create", Description = "创建抽奖活动" });
            //cmds.Add(new() { Command = "/luck", Description = "本群正在进行的抽奖" });
            //cmds.Add(new() { Command = "/stat", Description = "今天活跃统计" });
            //cmds.Add(new() { Command = "/stat_week", Description = "七天活跃统计" });
            //cmds.Add(new() { Command = "/filter", Description = "添加自动回复规则" });
            //cmds.Add(new() { Command = "/stop", Description = "删除自动回复规则" });
            //cmds.Add(new() { Command = "/filters", Description = "所有自动回复规则列表" });
            //cmds.Add(new() { Command = "/mute", Description = "禁言" });
            //cmds.Add(new() { Command = "/unmute", Description = "解除禁言" });
            //cmds.Add(new() { Command = "/ban", Description = "封禁" });
            //cmds.Add(new() { Command = "/unban", Description = "解除封禁" });
            //cmds.Add(new() { Command = "/kick", Description = "踢出成员" });
            //await botClient.SetMyCommandsAsync(cmds);

            #endregion
        }

        private Task _OnError(Exception exception, HandleErrorSource source)
        {
            var ErrorMessage = exception switch
            {
                ApiRequestException apiRequestException
                    => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            _logger.LogError(ErrorMessage);
            return Task.CompletedTask;
        }

        private async Task _OnUpdate(Update update)
        {
            System.Console.WriteLine("BotClient_OnUpdate:");
            System.Console.WriteLine(update.ToJson());

            await HandleUpdateAsync(bot, update, default);
        }

        private Task _OnMessage(Message msg, UpdateType type)
        {
            if (msg.Text is null) return Task.CompletedTask;

            System.Console.WriteLine("BotClient_OnMessage:");
            System.Console.WriteLine($"Received {type} '{msg.Text}' in {msg.Chat}");


            return Task.CompletedTask;
        }

        async Task HandleUpdateAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken)
        {
            IHandler hander = default!;

            switch (update.Type)
            {
                case UpdateType.Unknown:                    //未知
                    {

                    }
                    break;
                case UpdateType.Message:                    //消息
                    {
                        hander = new MessageHandler();
                    }
                    break;
                case UpdateType.InlineQuery:                //机器人内联查询
                    {
                        hander = new InlineQueryHandler();
                    }
                    break;
                case UpdateType.ChosenInlineResult:         //选择内联结果
                    {

                    }
                    break;
                case UpdateType.CallbackQuery:              //查询回调
                    {
                        hander = new CallbackQueryHandler();
                    }
                    break;
                case UpdateType.EditedMessage:              //编辑消息
                    {

                    }
                    break;
                case UpdateType.ChannelPost:                //当管理员或机器人在频道内发送消息时触发
                    {
                        hander = new ChannelPostHandler();
                    }
                    break;
                case UpdateType.EditedChannelPost:          //当管理员或机器人在频道内重新编辑已发送消息再次发送时触发
                    {
                        hander = new EditedChannelPostHandler();
                    }
                    break;
                case UpdateType.ShippingQuery:
                    break;
                case UpdateType.PreCheckoutQuery:
                    break;
                case UpdateType.Poll:                       //有调查投票的更新
                    {
                        
                    }
                    break;
                case UpdateType.PollAnswer:                 //投票答案
                    {

                    }
                    break;
                case UpdateType.MyChatMember:               //我的成员消息
                    {
                        hander = new MyChatMemberHandler();
                    }
                    break;
                case UpdateType.ChatMember:                 //成员消息
                    {
                        hander = new ChatMemberHandler();
                    }
                    break;
                case UpdateType.ChatJoinRequest:            //当群组开启【加入需要审核】 选项后，新用户点击【加入群组】时触发
                    {
                        hander = new ChatJoinRequestHandler();
                    }
                    break;
                default:

                    break;
            }

            try
            {
                if (hander == default)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    return;
                }

                await hander.Handle(bot, update, cancellationToken);
            }
            catch (OperationCanceledException ex)
            {
                _logger.LogWarning($"任务取消\r\n{ex.ToJson()}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToJson());
            }
        }


    }
}